<?php

namespace app\result\extend;

use app\model\extend\PIdea;
use app\result\BaseResult;

class IdeaResult extends BaseResult
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new  PIdea();
    }

    public function list($user_id, $args = [])
    {
        $page = $args['page'] ?? 1;
        $limit = $args['limit'] ?? 10;
        $keyword = $args['keyword'] ?? '';
        $where = [['user_id', '=', $user_id], ['del_time', '=', 0]];
        if ($keyword) {
            $where[] = ['title', 'like', "%{$keyword}%"];
        }
        $data = $this->model->data_list($where, 'id,title,content,created_at,updated_at', 'id desc', $page, $limit);
        $total = $this->model->data_count($where);
        if ($data) {
            foreach ($data as &$v) {
                $v['add_time'] = date('Y-m-d', strtotime($v['created_at']));
            }
            unset($v);
        }
        return self::success_return('success', [
            'total' => $total,
            'list' => $data,
        ]);
    }

    public function get($user_id, $args = [])
    {
        $id = $args['id'] ?? 0;
        if (!$id) {
            return self::error_return('数据错误');
        }
        $data = $this->model->data_get(['id' => $id, 'user_id' => $user_id, 'del_time' => 0]);
        return self::success_return('success', [
            'info' => $data,
        ]);
    }

    public function save($user_id, $args)
    {
        $id = $args['id'] ?? 0;
        $title = $args['title'] ?? '';
        $content = $args['content'] ?? '';
        if (!$content) {
            return self::error_return('请填写内容');
        } elseif (mb_strlen($content, 'utf-8') > 500) {
            return self::error_return('内容不能超过500字');
        }
        $baseData = [
            'title' => $title,
            'content' => $content,
            'user_id' => $user_id,
        ];
        if ($id) {
            $res = $this->model->data_update(['id' => $id], $baseData);
        } else {
            $res = $this->model->data_add($baseData);
        }
        if (!$res) {
            return self::error_return('保存失败');
        }
        return self::success_return('保存成功');
    }

    public function delete($user_id, $args)
    {
        $id = $args['id'] ?? 0;
        if (!$id) {
            return self::error_return('请选择要删除的数据');
        }
        $data = $this->model->data_get(['id' => $id, 'del_time' => 0]);
        if (!$data || $data['user_id'] != $user_id) {
            return self::error_return('只能删除自己的数据');
        }
        $this->model->data_del_soft(['id' => $id], 'del_time', time());
        return self::success_return('删除成功');
    }
}
